﻿using H2.NET.Business;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Workflow.DwzCode;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using H2.NET.Web.Pages.SMD.Helper;
using H2.NET.Common;
using H2.NET.Data.Common;
using System.Data;
using System.IO;
using NPOI.SS.UserModel;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.Helper;

namespace H2.NET.Web.Pages.SMD
{
    public partial class DeliveryBatchDevice : BasePage
    {
        public List<t_StoreMasterData> data = new List<t_StoreMasterData>();
        public DataTable deliveryType = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            ConfigService configService = new ConfigService();
            var qIncidents = AksRequest.GetString("incidents");
            var incidents = qIncidents.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            data = (t_StoreMasterData._Process == "Store Deposit Receive" & t_StoreMasterData._Incident.In(incidents)).List<t_StoreMasterData>(Storage.Context1).ToList();
            deliveryType = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_FFFS')").Tables[0];
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                var incidents = AksRequest.GetFormString("Incident").Split(',');
                foreach (var incidentStr in incidents) 
                {
                    var meipinNO = AksRequest.GetFormString("MeiPinNo" + incidentStr);
                    var fullSetSN = AksRequest.GetFormString("FullSetSN" + incidentStr);
                    var deviceId = Utils.StrToInt(AksRequest.GetFormString("DeviceId" + incidentStr), 0);
                    var deliveryType = AksRequest.GetFormString("DeliveryType" + incidentStr);
                    if (String.IsNullOrEmpty(fullSetSN))
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.tip('请填写固定资产号!', 'info');", true);
                        return;
                    }
                    if (String.IsNullOrEmpty(meipinNO)) 
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.tip('请填写美萍号！', 'info');", true);
                        return;
                    }
                    if (deviceId == 0 )
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.tip('请选择设备!', 'info');", true);
                        return;
                    }
                    if (String.IsNullOrEmpty(deliveryType))
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.tip('请选择发放类型!', 'info');", true);
                        return;
                    }
                }
                
                foreach (var incidentStr in incidents)
                {
                    // 获流程实例
                    var incident = Convert.ToInt32(incidentStr);
                    var task = TaskHelper.GetTask("Store Deposit Receive", incident, "Delivery Device");
                    var taskapi = new TaskAPI(task.strTaskId);
                    var storeId = taskapi.GetStoreId("storeid");
                    t_smd_Store store = StoreService.GetSmdStoreById(storeId);
                    var meipinNO = AksRequest.GetFormString("MeiPinNo" + incidentStr);
                    var fullSetSN = AksRequest.GetFormString("FullSetSN" + incidentStr);
                    var deviceId = Utils.StrToInt(AksRequest.GetFormString("DeviceId" + incidentStr),0);
                    var deliveryType = AksRequest.GetFormString("DeliveryType" + incidentStr);

                    //更新设备表
                    t_smd_Device device = (t_smd_Device._DeviceID == deviceId).ListFirst<t_smd_Device>(Storage.Context3);
                    device.MeiPinNo = meipinNO;
                    device.FullSetSN = fullSetSN;
                    device.Status = Cache["Device_KC"].ToString();
                    device.DeliveryType = deliveryType;
                    Storage.Save(Storage.Context3, device);

                     //生成出货通知单
                    GenerateInvoice(device);

                    //删除用过的美萍号
                    (t_smd_Meiping._SerialNumber == meipinNO).Delete<t_smd_Meiping>(Storage.Context3);

                    // todo:保存业务数据
                    taskapi.Send();

                    var key = taskapi.GetVariableBySingleValue("AutoBusinessKey");
                    // 如果是空，就是手动发起的流程
                    if (string.IsNullOrEmpty(key)) continue;

                    // 新开门店自动发起流程
                    if (key == Constant.PROCESS_STORE)
                    {
                        #region 自动启动门店信息变更

                        TaskAPI taskAPI = new TaskAPI(TaskHelper.STORE_DATA_CHANGE_TASKID);
                        string applicationNo = GenerateApplicationNo(taskAPI);

                        taskAPI["ParentProcess"] = taskapi.Process;
                        taskAPI["ParentIncident"] = taskapi.Incident;
                        taskAPI["AutoBusinessKey"] = key;
                        taskAPI["BlankVlue"] = taskapi.GetVariableBySingleValue("BlankVlue");
                        taskAPI["Actions"] = "ChangeStore";
                        taskAPI.InitTask(UserAPI, applicationNo);
                        taskAPI.Summary = "提交门店信息变更/" + TaskHelper.getSummary(taskapi.Summary);
                        taskAPI.SetStoreDataChangeRecipient(store.Region,store.Province,"Store");

                        t_Assessment ass = TaskHelper.InitAssessment(taskAPI, UserAPI);
                        Storage.Save(Storage.Context1, ass);

                        taskAPI.Send();

                        (t_Assessment.process == taskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                        {
                            p.Incident = taskAPI.Incident;
                        });

                        #endregion

                        #region 自动启动合同信息变更

                        taskAPI = new TaskAPI(TaskHelper.STORE_DATA_CHANGE_TASKID);
                        applicationNo = GenerateApplicationNo(taskAPI);

                        taskAPI["ParentProcess"] = taskapi.Process;
                        taskAPI["ParentIncident"] = taskapi.Incident;
                        taskAPI["AutoBusinessKey"] = key;
                        taskAPI["BlankVlue"] = storeId;
                        taskAPI["Actions"] = "ChangeContract";
                        taskAPI.InitTask(UserAPI, applicationNo);
                        taskAPI.Summary = "提交合同信息变更/" + TaskHelper.getSummary(taskapi.Summary);
                        taskAPI.SetStoreDataChangeRecipient(store.Region, store.Province, "Contract");

                        ass = TaskHelper.InitAssessment(taskAPI, UserAPI);
                        Storage.Save(Storage.Context1, ass);

                        taskAPI.Send();

                        (t_Assessment.process == taskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                        {
                            p.Incident = taskAPI.Incident;
                        });

                        #endregion
                    }
                    else if (key == Constant.PROCESS_DEVICEISSUED)
                    {
                        // 自动发起设备主数据变更
                        taskapi.SendProcess(UserAPI, key, "ChangeDevice",
                            H2.NET.Web.Workflow.Helper.TaskHelper.STORE_DATA_CHANGE_TASKID,
                           "提交设备信息变更/" + TaskHelper.getSummary(taskapi.Summary));

                        // 自动发起合同主数据变更
                        taskapi.SendProcess(UserAPI, key, "ChangeContract",
                            H2.NET.Web.Workflow.Helper.TaskHelper.STORE_DATA_CHANGE_TASKID,
                            "提交合同信息变更/" + TaskHelper.getSummary(taskapi.Summary));
                    }
                }
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { window.opener.reload(); closeWin(); } });", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.tip('" + Resources.Global.C_00_Failed + "');", true);
            }
        }

        #region 生成出货单
        protected void GenerateInvoice(t_smd_Device device) {
         // todo: 生成出货通知单
            t_smd_Store store = (t_smd_Store._StoreID == device.StoreID).ListFirst<t_smd_Store>(Storage.Context3);
            IWorkbook hssfworkbook;
            using (FileStream file = new FileStream(Server.MapPath("~/") + "Pages\\SMD\\Excel\\出库通知单20140009pc.xls", FileMode.Open, FileAccess.Read))
            {
                hssfworkbook = WorkbookFactory.Create(file);
            }
            ISheet sheet = hssfworkbook.GetSheetAt(0);

            t_smd_ShipOrderNumber shipNumber = (t_smd_ShipOrderNumber._YearOn == DateTime.Now.Year).ListFirst<t_smd_ShipOrderNumber>(Storage.Context3);
            if (shipNumber == null)
            {
                shipNumber = new t_smd_ShipOrderNumber();
                shipNumber.YearOn = DateTime.Now.Year;
                shipNumber.Sequence = 1;
            }
            else
            {
                shipNumber.Sequence = shipNumber.Sequence + 1;
            }
            Storage.Save(Storage.Context3, shipNumber);
            string number = shipNumber.YearOn + shipNumber.Sequence.ToString().PadLeft(4, '0');
            sheet.GetRow(4).GetCell(3).SetCellValue(number);
            sheet.GetRow(6).GetCell(1).SetCellValue(store.StoreName);
            sheet.GetRow(7).GetCell(1).SetCellValue("地址：" + device.Address);
            sheet.GetRow(8).GetCell(1).SetCellValue("电话：" + device.Contacts);
            sheet.GetRow(9).GetCell(1).SetCellValue("联系人：" + device.ContactNumber);
            sheet.GetRow(11).GetCell(1).SetCellValue(device.FJDate == null ? "" : device.FJDate.Value.ToString("yyyy/MM/dd"));
            int i = 0;
            int baseRow = 15;
            if (!string.IsNullOrEmpty(device.DispenserModel))
            {
                sheet.GetRow(baseRow).GetCell(0).SetCellValue(++i);
                sheet.GetRow(baseRow).GetCell(1).SetCellValue("调色机");
                sheet.GetRow(baseRow).GetCell(2).SetCellValue(device.DispenserModel);
                sheet.GetRow(baseRow).GetCell(3).SetCellValue(1);
                baseRow++;
            }
            if (!string.IsNullOrEmpty(device.ShakerModel))
            {
                sheet.GetRow(baseRow).GetCell(0).SetCellValue(++i);
                sheet.GetRow(baseRow).GetCell(1).SetCellValue("震荡机");
                sheet.GetRow(baseRow).GetCell(2).SetCellValue(device.ShakerModel);
                sheet.GetRow(baseRow).GetCell(3).SetCellValue(1);
                baseRow++;
            }
            if (!string.IsNullOrEmpty(device.PcModel))
            {
                sheet.GetRow(baseRow).GetCell(0).SetCellValue(++i);
                sheet.GetRow(baseRow).GetCell(1).SetCellValue("电脑");
                sheet.GetRow(baseRow).GetCell(2).SetCellValue(device.PcModel);
                sheet.GetRow(baseRow).GetCell(3).SetCellValue(1);
                baseRow++;
            }
            sheet.GetRow(41).GetCell(1).SetCellValue(DateTime.Now.ToString("yyyy/MM/dd"));
            string path = Util.AppSettings("path") + @"\" + "CKD" + @"\";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            FileStream fs = File.Create(path + number + ".xls");
            hssfworkbook.Write(fs);
            fs.Close();

            device.ShipOrderNumber = number;
            Storage.Save(Storage.Context3, device);
        }
        #endregion
    }
}